package sc.core.auth;

import java.util.ArrayList;
import java.util.HashSet;

import sc.core.auth.enums.LoginTypeEnum;
import sc.core.auth.enums.PermissionEnum;
import sc.core.auth.enums.RoleEnum;
import sc.core.dal.daointerface.UserDAO;
import sc.core.dal.dataobject.UserInfoDO;
import sc.core.dal.dataobject.UserLoginDO;

public class UserManager {
	
	UserDAO userDAO;

	public UserInfoDO getLocalUserByLoginName(String loginName) {
		UserLoginDO userLoginDO = userDAO.selectUserLoginByTypeAndId(LoginTypeEnum.LOCAL.toString(), loginName);
		if (userLoginDO == null)
			return null;
		UserInfoDO userInfoDO = userDAO.selectUserInfoById(userLoginDO.getUserId());
		// TODO Now Mocked
//		if ("1".equals(loginName)) {
//			user = new UserDO("1", "c4ca4238a0b923820dcc509a6f75849b",
//					new Date(), "local", null, null);
//		} else if ("2".equals(loginName)) {
//			user = new UserDO("2", "c81e728d9d4c2f636f067f89cc14862c",
//					new Date(), "local", null, null);
//		}
//
		if (userInfoDO != null) {
			userInfoDO.setUserLoginDO(userLoginDO);
			userInfoDO.setRoles(getRoleByLoginId(loginName));
			if (!userInfoDO.getRoles().isEmpty()) {
				userInfoDO.setPermissions(getPermissionByRoles(userInfoDO.getRoles()));
			}
		}
		return userInfoDO;
	}

	public ArrayList<RoleEnum> getRoleByLoginId(String loginId) {
		ArrayList<RoleEnum> roles = new ArrayList<RoleEnum>();
		// TODO Now Mocked
		if ("1".equals(loginId)) {
			roles.add(RoleEnum.ADMIN);
		} else if ("2".equals(loginId)) {
			roles.add(RoleEnum.CUSTOMER);
		}

		return roles;
	}

	public ArrayList<PermissionEnum> getPermissionByRoles(
			ArrayList<RoleEnum> roles) {
		ArrayList<PermissionEnum> dupPerms = new ArrayList<PermissionEnum>();
		if (roles == null || roles.isEmpty())
			return dupPerms;
		for (RoleEnum r : roles) {
			dupPerms.addAll(r.getPerms());
		}
		HashSet<PermissionEnum> distContainer = new HashSet<PermissionEnum>(
				dupPerms);
		ArrayList<PermissionEnum> distPerms = new ArrayList<PermissionEnum>(
				distContainer);
		return distPerms;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	
}
